//
//  SchoolViewController.m
//  jungoo
//
//  Created by Dang Quang Trung on 8/7/12.
//  Modifyed by Sinbad Flyce
//  Copyright (c) 2012 __ABOM__. All rights reserved.
//

#import "SchoolViewController.h"
#import "College.h"
#import "User.h"
#import "AppDelegate.h"
#import "YPickerView.h"
#import "Extensions.h"

@implementation SchoolViewController

@synthesize schoolMode = _schoolMode, autocompleteView = _autocompleteView;


#pragma mark - Private Method

- (void)onSetAutocompleteDataSource:(NSArray*)aDataSource
{
    _autocompleteView.dataSource = aDataSource;
    _autocompleteView.keyName = @"college";
    _autocompleteView.delegate = (id)self;
}

- (void)asyncLoadColleges
{
    if ([JGoUtility sharedColleges] == nil) {
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 
        
        dispatch_async(queue, ^{
            
            NSError *error = nil;
            NSArray *colleges = [JGoAPI getColleges:&error];
            
            if (error) {
                LOG(@"%@",[error localizedDescription]);
            }
            else {
                
                [self performSelectorOnMainThread:@selector(onSetAutocompleteDataSource:) 
                                       withObject:colleges 
                                    waitUntilDone:YES];
                [JGoUtility setColleges:colleges];
            }
        });  
    }
    else {
        [self onSetAutocompleteDataSource:[JGoUtility sharedColleges]];
    }
    
}

- (void)applyAppearance
{        
    [self.navigationItem setHidesBackButton:YES];
    
    [self setBackButtonImageActiveName:nil 
                          inactiveName:@"back-button" 
                                target:self 
                                action:@selector(back:)];
    
    [self setRightButtonImageActiveName:nil 
                           inactiveName:@"done-button" 
                                 target:self 
                                 action:@selector(done:)];
    
    [self setTitle:@"School"];
    [self.tableView setAllowsSelection:NO];

    _autocompleteView = [[AutocompleteView alloc] initWithFrame:CGRectMake(0, 55, 320, 371)];
    
    dataSource = [NSMutableArray new];
    [dataSource addObject:[[JGoUtility sharedCreateAccount] objectForKey:@"college"] ? [[JGoUtility sharedCreateAccount] objectForKey:@"college"] : @""];
    [dataSource addObject:[[JGoUtility sharedCreateAccount] objectForKey:@"c_year"] ? [[JGoUtility sharedCreateAccount] objectForKey:@"c_year"] : @""];       
        
    YPickerView *yearPicker = (id)[[yearView viewWithTag:1] viewWithTag:11];
    yearPicker.year = [dataSource objectAtIndex:1];
}

- (void)showYearView:(BOOL)bShow
{
    if (bShow) {
        CGRect yvRect = CGRectMake(0, 460, 320, 460);
        
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.3];
        [self.navigationController.view addSubview:yearView];
        yearView.frame = yvRect;
        yvRect = CGRectMake(0, 20, 320, 416);
        yearView.frame = yvRect;
        [UIView commitAnimations];
    }
    else {
        
        [UIView animateWithDuration:0.3 
                         animations:^{
                             CGRect dobRect = CGRectMake(0, 460, 320, 460);
                             yearView.frame = dobRect;                               
                         }
                         completion:^(BOOL finished){    
                             [yearView removeFromSuperview];
                         }];                
    }
}


#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self applyAppearance];
    [self asyncLoadColleges];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc
{
    [dataSource release];
    [_autocompleteView release];    
    [super dealloc];
}

#pragma mark - Action

- (void)done:(id)sender
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
           
    [[JGoUtility sharedCreateAccount] setValue:[dataSource objectAtIndex:0]                                                     
                                         forKey:@"college"];
    [[JGoUtility sharedCreateAccount] setValue:[dataSource objectAtIndex:1] 
                                        forKey:@"c_year"];
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)selectYear:(id)sender
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    [self showYearView:YES];
}

- (IBAction)doneYearView:(id)sender
{   
    YPickerView *yearPicker = (id)[[yearView viewWithTag:1] viewWithTag:11];
    NSString *yearString = yearPicker.year;
    [dataSource replaceObjectAtIndex:1 withObject:yearString];
    [self showYearView:NO];
    [self.tableView reloadData];

}

#pragma mark - TableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *tableHeader = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 10)] autorelease];
    tableView.backgroundColor = [UIColor clearColor];
    
    return tableHeader;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    
    switch (indexPath.row) {
        case 0: {
            cell = cell1;            
            [cell1 fieldTextWithTag:1].delegate = (id)self;
            [cell1 fieldTextWithTag:1].text = [dataSource objectAtIndex:0];
            break;
        }
            
        case 1: {
            cell = cell2;
            [[cell buttonWithTag:1] addTarget:self 
                                action:@selector(selectYear:) 
                      forControlEvents:UIControlEventTouchUpInside];
            UILabel *readText = [cell2 titleTextWithTag:2];
            readText.text = [dataSource objectAtIndex:1];
            break;
        }
    }
    
    return cell;
}

#pragma mark - TextField Delegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    UITableViewCell *cell = (id)textField.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 358, 0)];
    [self.tableView scrollToRowAtIndexPath:indexPath 
                          atScrollPosition:UITableViewScrollPositionNone 
                                  animated:NO];
    
    [self.view addSubview:_autocompleteView];
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] 
                          atScrollPosition:UITableViewScrollPositionNone 
                                  animated:YES];
    
    UITableViewCell *cell = (id)textField.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    if ([indexPath isKindOfClass:[NSIndexPath class]]) {        
        [dataSource replaceObjectAtIndex:0 withObject:textField.text];
    }
    
    [_autocompleteView searchAutocompleteEntriesWithSubstring:@""];
    [_autocompleteView removeFromSuperview];
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    UITableViewCell *cell = (id)textField.superview.superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    if ([indexPath isKindOfClass:[NSIndexPath class]]) {
        [dataSource replaceObjectAtIndex:0 withObject:textField.text];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *substring = [NSString stringWithString:textField.text];    
    substring = [substring stringByReplacingCharactersInRange:range withString:string];
    [_autocompleteView searchAutocompleteEntriesWithSubstring:substring];
    [_autocompleteView setUserInfo:textField];
    
    return YES;
}

#pragma mark - AutocompleteView Delegate

- (void)autocompleteView:(AutocompleteView *)autocompleteView didSeletedWithString:(NSString *)aString
{
    UITextField *textField = (id)autocompleteView.userInfo;
    textField.text = aString;
}

@end
